<?php
namespace Admin\Model;

use Think\Model;

class CourseModel extends Model {


    public function getCourseByWhere($where,$limit='') {
        is_null($where) && $where = '';
        return $this->where($where)->limit($limit)->select();
    }


    public function getCourseByTid($tid) {
        return $this->where('teacher_id = '.$tid)->select();
    }

    public function getCourseName($id) {
        return $this->where('id = '.$id)->getField('name');
    }

    public function _get ($id) {
        return $this->find($id);
    }

    public function _add ($data) {

        if ($this->checkRepeatName($data['name'],$data['teacher_id'])) return '100901';

        $flag = $this->add($data);
        if ($flag !== false)  return '000000';
        return '111111';
    }

    public function _edit($data) {

        if ($this->checkRepeatName($data['name'],$data['teacher_id'],$data['id'])) return '100901';

        $flag = $this->save($data);
        if ($flag !== false) return '000000';
        return '111111';

    }

    public function _del($id) {
        $flag = $this->delete($id);
        if ($flag !== false) return '000000';
        return '111111';
    }


    /**
     * 检查同一个老师是否存在重复课程名字
     *
     * @param $name
     * @param $tid
     * @return bool
     */
    protected function checkRepeatName($name,$tid,$id = null) {
        $map['name'] = $name;
        $map['teacher_id'] = $tid;
        !is_null($id) && $map['id'] = array('neq',$id);
        $c = $this->where($map)->find();
        if (!empty($c)) return true;
        return false;
    }

}